/*
	@descript 
		a simple script which can help you download your favouriate songs from douban.com
		[thanks to dbfmdb.sinaapp.com]
	@author 
		sodarfish@163.com
	1. open your Google Chrome [the best browser in the world], login and goto http://douban.fm/mine?type=liked
	2. press F12 to open console
	3. select the 'console' tab and copy & paste the codes here into console, press 'Enter'
	4. when all things done, you will get a song list and a download button at the bottom of page! then ... Have Fun!
*/
var totalPages = 10;
var firstPage = 1;
var page=firstPage;
var numPerPage = 15;
var counter = 0;
var allsongs = [];
var pagesParsingDone = false;
var dumpSongs = function(){
	console.log('[done] Please close the console and Check the song list at the bottom of current page!');
	var div = $('<div id="__collected_songs"></div>');
	div.css({
			'background-color':'#333333','width':'500px',
			'border':'1px solid #cccccc',
			'color' : 'skyblue',
			'padding':'5px'
	});
	var m = allsongs.length + ' songs were collected from page ' + firstPage + ' to ' + (page <= totalPages ? page : totalPages);
	m += '<br/>all songs listed below, enjoy!';
	m += '<br/>You can <a style="color:pink" href="javascript:void(0);" onclick="dl();return false;">download all</a>'
	var title = $('<div></div>');
	div.append(title);
	title.css({ 'font-size':'16px','color':'#eee','font-weight':'bold'});
  title.html(m);
	for(var i=0;i<allsongs.length;i++){
		var s = allsongs[i];
		div.append($('<div>' + (i + 1) + '.&nbsp;' + s.title + '-' + s.artist + '<a style="color:pink" href="' + s.url + '" download="' + s.title + '-' + s.artist + '"> download it</a></div>'));
	}
	$('body').append(div);
	div.css( {'position':'absolute','z-index':'9999', 'left' : ($(window).width() - 500)/2 + 'px', 'top' : div.offset().top + 'px'});
}
var dl = function(){
	$('#__collected_songs').find('a').each(function(a){
		
		if(this.download)
			this.click();	
	});
}
console.log('start collecting songs from ' + page + ' to ' + totalPages + ' pages.');
var set_cookie = function(dict, time) {
    var date = new Date();
    date.setTime(date.getTime() + time);
    var expires = "; expires=" + date.toGMTString();
    for (var i in dict) {
      document.cookie = i + "=" + dict[i] + expires + "; domain=douban.fm; path=/"
    }
}
var getDownloadInfo = function(songs){
	  for(var i=0;i<songs.length;i++) {
      var song = songs[i];
      set_cookie({'start': song.sid + 'g' + song.ssid + 'g0'}, 10 * 1000);//cookie start == song id
	    $.ajax({
        type:"GET",url:'http://douban.fm/j/mine/playlist?type=n&h=&channel=0&from=mainsite&r=4941e23d79'
        ,async:false,dataType:"json"
        ,success:function(songs){
					if(songs.song && songs.song[0]) {
					   allsongs.push(songs.song[0]);	
					   console.log(songs.song[0].title + ' loaded!')
					}
        }
      });	
	  }
	  counter--;
	  if(counter == 0 && pagesParsingDone) {//all done
	  	dumpSongs();	
	  }
}
for(;page<=totalPages;page++) {
    n = (page - 1) * numPerPage;
    var url = "http://douban.fm/mine?start=" + n + "&type=liked";
    var sids = [];
    $.ajax({
        type:"GET"
        ,url:url
        ,async:false
        ,dataType:"html"
        , success:function(html){
            numPerPage = $(html).find("div.info_wrapper").length;/*update songs per page*/
            $(html).find("div.info_wrapper").each(function(s) {
                var title =$(this).find("p.song_title").first().text()+"-"+
                $(this).find("p.performer").first().text()+"-"+
                $(this).find("p.source>a").first().text();
                var sid = $(this).find("div.action").attr("sid");
                sids.push(sid);
            });
            console.log('collected ' + sids.length + 'songs from page ' + page );
        }
    });
		
    //get 'ssid' of song from dbfmdb
    //( use codegallery.sinaapp.com as a proxy to provide JSONP callback) (JSONP is asynchronous)
    if(sids.length > 0) {
    	if(page ==totalPages)
    		pagesParsingDone = true;
    	counter++;//working counter
	    $.getJSON('http://codegallery.sinaapp.com/api/dbfmdb/?callback=?&sids=' + sids.join('_'), function(songs) {
	    	  if(!songs) {
	    	     console.log('got error from CodeGallery! sids=' + sids);
	    	     counter--;
	    	  } else  {
	    			getDownloadInfo(songs);
	    		}
			});
    } else {
    	console.log('[warn]we got nothing from page '+ page + ',which means the page number is wrong, just break.');
    	pagesParsingDone = true;
    	break;
    }
    
}